/**
 * MySQL 连接测试脚本
 */

const mysql = require('mysql2/promise');
require('dotenv').config();

const DB_CONFIG = {
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 3306,
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'tkshop'
};

async function testConnection() {
  let connection;
  
  try {
    console.log('测试 MySQL 连接...');
    console.log('连接配置:', {
      host: DB_CONFIG.host,
      port: DB_CONFIG.port,
      user: DB_CONFIG.user,
      database: DB_CONFIG.database
    });
    
    connection = await mysql.createConnection(DB_CONFIG);
    
    console.log('✅ MySQL 连接成功');
    
    // 测试数据库操作
    const [tables] = await connection.query('SHOW TABLES');
    
    console.log('数据库中的表:');
    tables.forEach(table => {
      console.log(`  - ${Object.values(table)[0]}`);
    });
    
    // 测试 t_product 表
    const tableExists = tables.some(table => Object.values(table)[0] === 't_product');
    if (tableExists) {
      const [rows] = await connection.query('SELECT COUNT(*) as count FROM t_product');
      const count = rows[0].count;
      console.log(`t_product 表中有 ${count} 条记录`);
      
      // 显示表结构
      const [columns] = await connection.query('DESCRIBE t_product');
      console.log('\nt_product 表结构:');
      columns.forEach(column => {
        console.log(`  ${column.Field}: ${column.Type} ${column.Null === 'NO' ? 'NOT NULL' : 'NULL'}`);
      });
    } else {
      console.log('⚠️  t_product 表不存在，请运行初始化脚本');
    }
    
  } catch (error) {
    console.error('❌ MySQL 连接失败:', error.message);
    
    if (error.code === 'ER_BAD_DB_ERROR') {
      console.log('💡 数据库不存在，请运行: npm run db:init');
    } else if (error.code === 'ER_ACCESS_DENIED_ERROR') {
      console.log('💡 请检查数据库用户名和密码配置');
    } else if (error.code === 'ECONNREFUSED') {
      console.log('💡 请确保 MySQL 服务正在运行');
    }
    
    process.exit(1);
  } finally {
    if (connection) {
      await connection.end();
      console.log('连接已关闭');
    }
  }
}

if (require.main === module) {
  testConnection();
}

module.exports = { testConnection };